package cn.stylefeng.guns.modular.rest.transport;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.core.util.MapUtils;
import cn.stylefeng.guns.modular.agv.model.params.FeedbackTaskRS;
import cn.stylefeng.guns.modular.agv.service.HikAgvTaskService;
import cn.stylefeng.guns.modular.agv.util.HikApiUtils;
import cn.stylefeng.guns.modular.agv.util.HikRsVo;
import cn.stylefeng.guns.modular.agv.util.TustApiUtils;
import cn.stylefeng.guns.modular.basic.entity.BasicAddress;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.entity.BasicPrivatecar;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.model.params.*;
import cn.stylefeng.guns.modular.basic.model.result.BasicCustomerResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicDriverResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPrivatecarResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.storage.entity.HxCollectionLocation;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageOut;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageOutResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxCollectionLocationService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOutService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageStockService;
import cn.stylefeng.guns.modular.order.entity.OrderOutpreparePlatooncar;
import cn.stylefeng.guns.modular.order.entity.OrderTransport;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.service.OrderOutpreparePlatooncarService;
import cn.stylefeng.guns.modular.order.service.OrderTransportService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.rest.transport.vo.TrayNumberVo;
import cn.stylefeng.guns.modular.transport.entity.TDispatch;
import cn.stylefeng.guns.modular.transport.entity.TransportReceipt;
import cn.stylefeng.guns.modular.transport.model.params.*;
import cn.stylefeng.guns.modular.transport.model.result.TDispatchResult;
import cn.stylefeng.guns.modular.transport.model.result.TransportDispatchResult;
import cn.stylefeng.guns.modular.transport.model.result.TransportMsgResult;
import cn.stylefeng.guns.modular.transport.model.result.TransportReceiptResult;
import cn.stylefeng.guns.modular.transport.service.*;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.FileInfo;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.FileInfoService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 运力
 */
@Controller
@RequestMapping("/rest/transportCar")
public class restTransportCarController extends BaseController {

    @Autowired
    private UserAop userAop;
    @Autowired
    private TransportDispatchService transportDispatchService;
    @Autowired
    private OrderTransportService orderTransportService;
    @Autowired
    private TransportCostService transportCostService;
    @Autowired
    private BasicPutgoodsService basicPutgoodsService;
    @Autowired
    private HikAgvTaskService hikAgvTaskService;

    @Value("${hxl.api.url}")
    private String hxlApiUrl;

    /**
     * 查询配送注意事项
     */
    @ResponseBody
    @RequestMapping("/findCareful")
    public ResponseData findCareful(BasicPutgoodsParam basicPutgoodsParam) {
        BasicPutgoods result = basicPutgoodsService.getById(basicPutgoodsParam.getId());
        return ResponseData.success(result);
    }

    /**
     * 费用信息
     */
    @ResponseBody
    @RequestMapping("/cost")
    public ResponseData cost(TransportCostParam transportCostParam) {
        return ResponseData.success(transportCostService.findListBySpec(transportCostParam, null));
    }

    /**
     * APP车辆选择
     * 查询已配置车辆
     */
    @ResponseBody
    @RequestMapping("/findCarListBySpecToo")
    public ResponseData findCarListBySpecToo(TransportDispatchParam transportDispatchParam, String tstate, String getUnit, String getLocation) {
        User user = userAop.getUser();
        transportDispatchParam.setDeliverId(user.getDeliverId());
        transportDispatchParam.setDeptId(user.getDeptId());
        String token = "Wait";
        String dispatch = "yunshu";
        if (ToolUtil.isNotEmpty(tstate)) {
            token = "";
        }
        List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecToo(transportDispatchParam, getUnit, getLocation, token, null, dispatch, user.getOperateId());
        for (TransportDispatchResult r : list) {
            OrderTransportParam orderTransportParam = new OrderTransportParam();
            orderTransportParam.setDeptId(user.getDeptId());
            orderTransportParam.setTstate("dispatch");
            orderTransportParam.setOrderNumber(r.getDispatchNumber());
            if (ToolUtil.isNotEmpty(tstate)) {
                orderTransportParam.setTstate("too");
            }
            List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam, r.getCarId(), null, user.getOperateId());
            r.setList(list2);
        }
        return ResponseData.success(list);
    }

    /**
     * APP车辆选择
     * 查询已配置车辆
     */
    @ResponseBody
    @RequestMapping("/findCarListBySpecYunShuZhongToo")
    public ResponseData findCarListBySpecYunShuZhongToo(TransportDispatchParam transportDispatchParam, String tstate) {
        User user = userAop.getUser();
        transportDispatchParam.setDeliverId(user.getDeliverId());
        transportDispatchParam.setDeptId(user.getDeptId());
        String token = "Wait";
        String dispatch = "yunshu";
        if (ToolUtil.isNotEmpty(tstate)) {
            token = "";
        }
        List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecYunShuZhongToo(transportDispatchParam, token, null, dispatch, user.getOperateId());
        for (TransportDispatchResult r : list) {
            OrderTransportParam orderTransportParam = new OrderTransportParam();
            orderTransportParam.setDeptId(user.getDeptId());
            orderTransportParam.setTstate("dispatch");
            orderTransportParam.setOrderNumber(r.getDispatchNumber());
            if (ToolUtil.isNotEmpty(tstate)) {
                orderTransportParam.setTstate("too");
            }
            List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam, r.getCarId(), null, user.getOperateId());
            r.setList(list2);
        }
        return ResponseData.success(list);
    }

    /**
     * 收货单位
     * 查询运输中运单
     */
    @ResponseBody
    @RequestMapping("/findCarListBySpecYunShuZhongTooGetUnit")
    public ResponseData findCarListBySpecYunShuZhongTooGetUnit(TransportDispatchParam transportDispatchParam, String tstate) {
        User user = userAop.getUser();
        transportDispatchParam.setDeliverId(user.getDeliverId());
        transportDispatchParam.setDeptId(user.getDeptId());
        String dispatch = "yunshu";
        if (user.getGetUnitId() != null) {
            transportDispatchParam.setGetUnit(user.getGetUnit());
            List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecYunShuZhongTooGetUnit(transportDispatchParam, dispatch, user.getOperateId());
            for (TransportDispatchResult r : list) {
                OrderTransportParam orderTransportParam = new OrderTransportParam();
                orderTransportParam.setDeptId(user.getDeptId());
                orderTransportParam.setTstate("dispatch");
                orderTransportParam.setOrderNumber(r.getDispatchNumber());
                if (ToolUtil.isNotEmpty(tstate)) {
                    orderTransportParam.setTstate("too");
                }
                List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam, r.getCarId(), null, user.getOperateId());
                r.setList(list2);
            }
            return ResponseData.success(list);
        }
        return ResponseData.success();
    }

    /**
     * APP车辆选择
     * 查询已配置车辆
     */
    @ResponseBody
    @RequestMapping("/findCarPageListBySpecToo")
    public LayuiPageInfo findCarPageListBySpecToo(TransportDispatchParam transportDispatchParam, String tstate, String getUnit, String getLocation) {
        User user = userAop.getUser();
        transportDispatchParam.setDeliverId(user.getDeliverId());
        transportDispatchParam.setDeptId(user.getDeptId());
        String token = "Wait";
        String dispatch = "yunshu";
        if (ToolUtil.isNotEmpty(tstate)) {
            token = "";
        }
        LayuiPageInfo page = this.transportDispatchService.findCarPageListBySpecToo(transportDispatchParam, getUnit, getLocation, token, null, dispatch, user.getOperateId());
        if (page.getCount() > 0) {
            List<TransportDispatchResult> list = page.getData();
            for (TransportDispatchResult r : list) {
                OrderTransportParam orderTransportParam = new OrderTransportParam();
                orderTransportParam.setDeptId(user.getDeptId());
                orderTransportParam.setTstate("dispatch");
                orderTransportParam.setOrderNumber(r.getDispatchNumber());
                if (ToolUtil.isNotEmpty(tstate)) {
                    orderTransportParam.setTstate("too");
                }
                List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam, r.getCarId(), null, user.getOperateId());
                r.setList(list2);
            }
            page.setData(list);
        }
        return page;
    }

    @Autowired
    private BasicDriverService basicDriverService;

    /**
     * 货运
     * 查询我的运单
     */
    @ResponseBody
    @RequestMapping("/findCarListBySpecToo2")
    public ResponseData findCarListBySpecToo2(TransportDispatchParam transportDispatchParam, String tstate, String getUnit, String getLocation, String findtype) {
        User user = userAop.getUser();
        Long operateId = null;
        if (findtype.equals("1")) {
            BasicDriverParam basicDriverParam = new BasicDriverParam();
            basicDriverParam.setUserId(user.getUserId());
            BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam, null);
            BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
            if (basicDriverResult != null) {
                BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
                BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
                basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null, null);
            } else {
                return ResponseData.success();
            }
            if (basicPrivatecarResult == null) {
                return ResponseData.success();
            }
            transportDispatchParam.setCarId(Long.parseLong(basicPrivatecarResult.getId().toString()));
        } else {
            operateId = user.getOperateId();
            transportDispatchParam.setDeptId(user.getDeptId());
        }
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String token = "";
        String dispatch = "yunshu";
        if (findtype.equals("3")) {
            dispatch = "shenhe";
        }
        Map<String, List<String>> sginKeyMap = new HashMap<>();
        List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecToo(transportDispatchParam, getUnit, getLocation, token, null, dispatch, operateId);
        List<String> clientList;

        for (TransportDispatchResult r : list) {
            OrderTransportParam orderTransportParam = new OrderTransportParam();
            orderTransportParam.setTstate("too");
            orderTransportParam.setOrderNumber(r.getDispatchNumber());
            List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam, r.getCarId(), dispatch, null);
            if(ToolUtil.isEmpty(operateId)){
                operateId = r.getOperateId();
            }
            r.setList(list2);
            if ("运输中".equals(r.getTstate()) && ToolUtil.isNotEmpty(r.getSginKey()) && ToolUtil.isEmpty(r.getSginUrl())) {
                if (list2 != null && list2.size() > 0) {
                    for (OrderTransportResult obj : list2) {
                        if (sginKeyMap.get(r.getSginKey()) == null) {
                            clientList = new ArrayList<>();
                            clientList.add(obj.getXlbClientId());
                            sginKeyMap.put(r.getSginKey(), clientList);
                        }else{
                        	if(!sginKeyMap.get(r.getSginKey()).contains(obj.getXlbClientId())){
								sginKeyMap.get(r.getSginKey()).add(obj.getXlbClientId());
							}
						}
                    }
                }

            }
        }

        Map<String,String> sginUrlMap = new HashMap<>();
        // 请求接口，获取对应的url
        boolean isEtcSign = false;
        if(!sginKeyMap.isEmpty()){
			BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
			basicCustomerParam.setCustomerOperateId(operateId.intValue());
			BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
			if ("是".equals(cr.getIsEtcSign())) {
                isEtcSign = true;
				BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
				oauth2tokenParam.setDeliverId(user.getDeliverId());
				oauth2tokenParam.setGsnumber(cr.getGsnumber());
				BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
				if (oauth2tokenResult != null) {
					//生成电子签约
					String etcSignDriverFindUrl = this.hxlApiUrl+"/hxl.open.tms.sign.url.driver.find";
					for(String key : sginKeyMap.keySet()){
						JSONObject etcSignDriverFindObj = new JSONObject();
						etcSignDriverFindObj.put("end_point", "APP");
						etcSignDriverFindObj.put("company_id", cr.getGsnumber());
						etcSignDriverFindObj.put("fids",ListUtil.of(key));
						etcSignDriverFindObj.put("client_ids",sginKeyMap.get(key));
						String etcSignGenRes = HttpRequest.post(etcSignDriverFindUrl)
								.timeout(60000)
								.contentType("application/json;charset=UTF-8")
								.header("Accept", "application/json")
								.header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(etcSignDriverFindObj.toString()).execute().body();
						if(ToolUtil.isNotEmpty(etcSignGenRes) && !etcSignGenRes.startsWith("Error")){
                            JSONObject etcSignGenObject = new JSONObject(etcSignGenRes);
                            if ("0".equals(etcSignGenObject.get("code").toString())) {
                                JSONObject jsonObject2 = new JSONObject(etcSignGenObject.get("data").toString());
                                if(jsonObject2.get("sign_url") != null){
                                    String sign_url = jsonObject2.get("sign_url").toString();
                                    sginUrlMap.put(key,sign_url);
                                    this.tDispatchService.lambdaUpdate()
                                            .eq(TDispatch::getSginKey,key)
                                            .set(TDispatch::getSginUrl,sign_url)
                                            .update();
                                }
                            }
                        }
					}

				}
			}
		}
        // 更新签约状态 和 对应的签约URL
        for (TransportDispatchResult r : list) {
            if(sginUrlMap.get(r.getSginKey()) != null){
                r.setSginUrl(sginUrlMap.get(r.getSginKey()));
            }
            if("运输中".equals(r.getTstate()) && ToolUtil.isNotEmpty(r.getSginUrl())){
                r.setEtcSignStat("签署");
            }else if("运输中".equals(r.getTstate()) && isEtcSign && ToolUtil.isEmpty(r.getSginKey())){
                r.setEtcSignStat("电子签");
            }
            for(OrderTransportResult obj : r.getList()){
                List<TransportReceipt> list1 = this.transportReceiptService.lambdaQuery()
                        .eq(TransportReceipt::getDispatchNumber, r.getDispatchNumber())
                        .eq(TransportReceipt::getXlbClientId, obj.getXlbClientId())
                        .list();
                for(TransportReceipt obj1 : list1){
                    if("运输中".equals(r.getTstate()) && ToolUtil.isNotEmpty(r.getSginKey()) && obj1 != null && "已送达".equals(obj1.getSdtstate())){
                        obj.setSdStat("验收");
                    }
                }
            }
        }


        return ResponseData.success(list);
    }

    /**
     * 货运 like
     * 查询我的运单
     */
    @ResponseBody
    @RequestMapping("/findCarListBySpecToo4")
    public ResponseData findCarListBySpecToo3(TransportDispatchParam transportDispatchParam, String tstate, String getUnit, String getLocation, String findtype) {
        User user = userAop.getUser();
        Long operateId = null;
        if (findtype.equals("1")) {
            BasicDriverParam basicDriverParam = new BasicDriverParam();
            basicDriverParam.setUserId(user.getUserId());
            BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam, null);
            BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
            if (basicDriverResult != null) {
                BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
                BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
                basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null, null);
            } else {
                return ResponseData.success();
            }
            if (basicPrivatecarResult == null) {
                return ResponseData.success();
            }
            transportDispatchParam.setCarId(Long.parseLong(basicPrivatecarResult.getId().toString()));
        } else {
            operateId = user.getOperateId();
            transportDispatchParam.setDeptId(user.getDeptId());
        }
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String token = "";
        String dispatch = "yunshu";
        if (findtype.equals("3")) {
            dispatch = "shenhe";
        }
        List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecToo2(transportDispatchParam, getUnit, getLocation, token, null, dispatch, operateId);
        for (TransportDispatchResult r : list) {
            OrderTransportParam orderTransportParam = new OrderTransportParam();
            orderTransportParam.setTstate("too");
            orderTransportParam.setOrderNumber(r.getDispatchNumber());
            List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam, r.getCarId(), dispatch, null);
            r.setList(list2);
//    		if(r.getTstate().equals("运输中")) {
//        		for (OrderTransportResult r1: list2) {
//        			TransportMsgParam transportMsgParam = new TransportMsgParam();
//        			transportMsgParam.setDispatchNumber(r.getDispatchNumber());
//        			transportMsgParam.setV1(r1.getGetLocationId()+"");
//        			transportMsgParam.setStatus("送达");
//        			TransportMsgResult transportMsgResult =  transportMsgService.findBySpec(transportMsgParam);
//        			if(transportMsgResult == null) {
//        				r.setSongdamake("show");
//        				break;
//        			}
//    			}
//    		}
        }
        return ResponseData.success(list);
    }

    /**
     * 货运
     * 查询我的运单
     */
    @ResponseBody
    @RequestMapping("/findCarListBySpecToo2Page")
    public LayuiPageInfo findCarListBySpecToo2Page(TransportDispatchParam transportDispatchParam, String tstate, String getUnit, String getLocation, String findtype) {
        User user = userAop.getUser();
        if (findtype.equals("1")) {
            if (ToolUtil.isNotEmpty(user.getPhone())) {
                transportDispatchParam.setCartel2(user.getPhone());
            }
            transportDispatchParam.setCartel(user.getAccount());
        }
        transportDispatchParam.setDeliverId(user.getDeliverId());
        transportDispatchParam.setDeptId(user.getDeptId());
        String token = "";
        String dispatch = "yunshu";
        if (findtype.equals("3")) {
            dispatch = "shenhe";
        }
        LayuiPageInfo page = this.transportDispatchService.findCarListBySpecToo2Page(transportDispatchParam, getUnit, getLocation, token, null, dispatch, user.getOperateId());
        if (page.getCount() > 0) {
            List<TransportDispatchResult> list = page.getData();
            for (TransportDispatchResult r : list) {
                OrderTransportParam orderTransportParam = new OrderTransportParam();
                orderTransportParam.setDeptId(user.getDeptId());
                orderTransportParam.setTstate("too");
                orderTransportParam.setOrderNumber(r.getDispatchNumber());
                List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam, r.getCarId(), dispatch, user.getOperateId());
                r.setList(list2);
            }
        }
        return page;
    }

    /**
     * 收货单位
     * 查询已完成运单
     */
    @ResponseBody
    @RequestMapping("/findCarListBySpecYiWanChengTooGetUnit")
    public LayuiPageInfo findCarListBySpecYiWanChengTooGetUnit(TransportDispatchParam transportDispatchParam, String tstate) {
        User user = userAop.getUser();
        transportDispatchParam.setDeliverId(user.getDeliverId());
        transportDispatchParam.setDeptId(user.getDeptId());
        String dispatch = "wancheng";
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        if (user.getGetUnitId() != null) {
            transportDispatchParam.setGetUnit(user.getGetUnit());
            layuiPageInfo = this.transportDispatchService.findCarListBySpecTooPage(transportDispatchParam, dispatch, user.getOperateId());
            if (layuiPageInfo.getCount() > 0) {
                List<TransportDispatchResult> list = layuiPageInfo.getData();
                for (TransportDispatchResult r : list) {
                    OrderTransportParam orderTransportParam = new OrderTransportParam();
                    orderTransportParam.setDeptId(user.getDeptId());
                    orderTransportParam.setOrderNumber(r.getDispatchNumber());
                    List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam, r.getCarId(), dispatch, user.getOperateId());
                    r.setList(list2);
                }
                layuiPageInfo.setData(list);
            }
            return layuiPageInfo;
        }
        return layuiPageInfo;
    }

    /**
     * 货运
     * 查询我的运单
     * 已完成
     */
    @ResponseBody
    @RequestMapping("/findCarListBySpecToo3")
    public LayuiPageInfo findCarListBySpecToo3(TransportDispatchParam transportDispatchParam, String tstate, String findtype) {
        User user = userAop.getUser();
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        Long operateId = null;
        if (findtype.equals("1")) {
            BasicDriverParam basicDriverParam = new BasicDriverParam();
            basicDriverParam.setUserId(user.getUserId());
            BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam, null);
            BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
            if (basicDriverResult != null) {
                BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
                BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
                basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null, null);
            } else {
                return layuiPageInfo;
            }
            if (basicPrivatecarResult == null) {
                return layuiPageInfo;
            }
            transportDispatchParam.setCarId(Long.parseLong(basicPrivatecarResult.getId().toString()));
        } else {
            operateId = user.getOperateId();
            transportDispatchParam.setDeptId(user.getDeptId());
        }
        transportDispatchParam.setDeliverId(user.getDeliverId());
        String dispatch = "wancheng";
        layuiPageInfo = this.transportDispatchService.findCarListBySpecTooPage(transportDispatchParam, dispatch, operateId);
        if (layuiPageInfo.getCount() > 0) {
            List<TransportDispatchResult> list = layuiPageInfo.getData();
            for (TransportDispatchResult r : list) {
                OrderTransportParam orderTransportParam = new OrderTransportParam();
                orderTransportParam.setOrderNumber(r.getDispatchNumber());
                List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam, r.getCarId(), dispatch, null);
                r.setList(list2);
            }
            layuiPageInfo.setData(list);
        }
        return layuiPageInfo;
    }

    @Autowired
    private TransportMsgService transportMsgService;

    @Autowired
    private TDispatchService tDispatchService;

    @Autowired
    private OrderOutpreparePlatooncarService orderOutpreparePlatooncarService;

    /**
     * 到仓装车
     */
    @RequestMapping("/editdaocang")
    @ResponseBody
    public ResponseData editdaocang(TDispatchParam tDispatchParam, String currentAddress, String longitude, String latitude, String sfyz, String openId) {
        User user = userAop.getUser();
        TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
        //解决参数中的 英文括号
        if (ToolUtil.isNotEmpty(currentAddress)) {
            currentAddress = currentAddress.replace("& #40;", "(");
            currentAddress = currentAddress.replace("& #41;", ")");
        }
        if (ToolUtil.isEmpty(sfyz)) {
            sfyz = "是";
        }
        if (dispatchResult != null) {
            if (dispatchResult.getTstate().equals("已定价")) {
                tDispatchParam.setId(dispatchResult.getId());
                tDispatchParam.setTstate("待发运");
                this.tDispatchService.update(tDispatchParam);

                TransportMsgParam transportMsgParam = new TransportMsgParam();
                transportMsgParam.setDispatchNumber(dispatchResult.getDispatchNumber());
                transportMsgParam.setStatus("到仓装车");
                transportMsgParam.setMsgType("司机");
                transportMsgParam.setContent(dispatchResult.getCarnumber() + "已到达仓库开始装车。" + "当前定位：" + currentAddress);
                transportMsgParam.setTimes(DateUtil.getDateS());
                transportMsgParam.setCreateUsername(user.getName());
                transportMsgParam.setDeliverId(dispatchResult.getDeliverId());
                transportMsgParam.setDeptId(dispatchResult.getDeptId());
                transportMsgParam.setSfyz(sfyz);
                transportMsgParam.setOpenId(openId);
                transportMsgService.add(transportMsgParam);
            }
        }
        return ResponseData.success();
    }

    @Autowired
    private BasicAddressService basicAddressService;

    @Autowired
    private BasicOperateService basicOperateService;

    /**
     * 主动 到仓校验
     */
    @RequestMapping("/editdaocangjiaoyan")
    @ResponseBody
    public ResponseData editdaocangjiaoyan(Long setLocationId, String longitude, String latitude, Long operateId) {
        if (ToolUtil.isEmpty(longitude) || ToolUtil.isEmpty(latitude) || setLocationId == null) {
            return ResponseData.error("缺少参数");
        }
        if (operateId != null) {
            BasicOperate basicOperate = basicOperateService.getById(operateId);
            if (basicOperate != null) {
                if (ToolUtil.isNotEmpty(basicOperate.getCheckWl())) {
                    if (basicOperate.getCheckWl().equals("否")) {
                        return ResponseData.success();
                    }
                }
            }
        }

        BasicAddress basicAddress = basicAddressService.getById(setLocationId);
        if (basicAddress != null) {
            if (ToolUtil.isNotEmpty(basicAddress.getSwitchWl())) {
                if (basicAddress.getSwitchWl().equals("1")) {
                    if (ToolUtil.isNotEmpty(basicAddress.getLongitude()) && ToolUtil.isNotEmpty(basicAddress.getLatitude())) {
                        double a = MapUtils.GetDistance(Double.parseDouble(basicAddress.getLongitude()), Double.parseDouble(basicAddress.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
                        double radius = Double.parseDouble(basicAddress.getSwitchBj());
                        if (radius < a) {
                            return ResponseData.error("您所在位置超出提货范围");
                        }
                    }
                }
            }
        }
        return ResponseData.success();
    }

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    @Autowired
    private HxStorageStockService hxStorageStockService;

    @Autowired
    private HxStorageOutService hxStorageOutService;


    @RequestMapping("/getTs")
    @ResponseBody
    public ResponseData getTs(TDispatchParam tDispatchParam) {
        SimpleDateFormat sdf10 = new SimpleDateFormat("yyyy-MM-dd");
        TDispatch tDispatch = tDispatchService.lambdaQuery()
                .eq(TDispatch::getDispatchNumber, tDispatchParam.getDispatchNumber())
                .one();
        if (tDispatch == null) {
            return ResponseData.success();
        }
        if (ToolUtil.isNotEmpty(tDispatch.getCarId())) {
            List<OrderOutpreparePlatooncar> orderOutpreparePlatooncarList = this.orderOutpreparePlatooncarService.lambdaQuery()
                    .eq(OrderOutpreparePlatooncar::getCarId, tDispatch.getCarId())
                    .eq(OrderOutpreparePlatooncar::getEstDeliveryDate, sdf10.format(new Date()))
                    .list();
            if (orderOutpreparePlatooncarList == null || orderOutpreparePlatooncarList.size() < 1) {
                return ResponseData.success();
            }
            List<String> xlbClientIdList = new ArrayList<>();
            for (OrderOutpreparePlatooncar obj : orderOutpreparePlatooncarList) {
                xlbClientIdList.add(obj.getClientId());
            }
            List<OrderTransportResult> orderTransportList = this.orderTransportService.findGetUnitVol(tDispatch.getOperateId(), xlbClientIdList);
            StringBuffer errStr = new StringBuffer();
            for (OrderTransportResult obj : orderTransportList) {
                if (errStr.length() > 0) {
                    errStr.append("<br>");
                }
                errStr.append("门店[").append(obj.getGetUnit())
                        .append("]应装").append(obj.getTotalVolume())
                        .append("已装").append(obj.getTooVolume());
            }
            if (errStr.length() > 0) {
                errStr.append("<br>");
                errStr.append("确定要操作吗？");
                return ResponseData.error(errStr.toString());
            }
        }

        return ResponseData.success();
    }

    /**
     * 离场发运
     */
    @RequestMapping("/editlicahng")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class, timeout = 180)
    public ResponseData editlicahng(TDispatchParam tDispatchParam, String currentAddress, String sfyz) {
        User user = userAop.getUser();
        TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
        //解决参数中的 英文括号
        if (ToolUtil.isNotEmpty(currentAddress)) {
            currentAddress = currentAddress.replace("& #40;", "(");
            currentAddress = currentAddress.replace("& #41;", ")");
        }
        if (ToolUtil.isEmpty(sfyz)) {
            sfyz = "是";
        }
        if (dispatchResult != null) {
            if (dispatchResult.getTstate().equals("待发运")) {
                BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
                basicCustomerParam.setCustomerOperateId(Integer.parseInt(dispatchResult.getOperateId().toString()));
                BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
                if (cr != null) {
                    List<TrayNumberVo> trayNumbers = new ArrayList<>();
                    OrderTransportParam orderTransportParam = new OrderTransportParam();
                    orderTransportParam.setDeptId(user.getDeptId());
                    List<OrderTransportResult> list = this.orderTransportService.findListBySpecNewsss(orderTransportParam, dispatchResult.getDispatchNumber(), user.getOperateId());
                    for (OrderTransportResult tr : list) {
                        if (ToolUtil.isNotEmpty(tr.getStockPort())) {
                            int indexOfChar = tr.getCustomerOrder().indexOf("_"); // 获取第一次出现"_"的索引位置
                            if (indexOfChar != -1) {
                                String result = tr.getCustomerOrder().substring(0, indexOfChar); // 从开头到"o"之间的子字符串
                                trayNumbers.add(TrayNumberVo.builder()
                                        .result(result)
                                        .stockPort(tr.getStockPort())
                                        .build());
                            }
                            //清空巷道
                            if (ToolUtil.isNotEmpty(cr.getAgvRobot()) && cr.getAgvRobot().equals("2")) {
                                if (ToolUtil.isNotEmpty(cr.getAgvBaseUrl())) {
                                    try{
                                        String stok = tr.getStockPort().replaceAll("通道", "");
                                        FeedbackTaskRS res = TustApiUtils.clear(cr.getAgvBaseUrl(), "H" + StringUtils.leftPad(stok, 3, "0"));
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                            } else if (ToolUtil.isNotEmpty(cr.getAgvRobot()) && cr.getAgvRobot().equals("1")) {
                                if (ToolUtil.isNotEmpty(cr.getAgvBaseUrl())) {
                                    String stok = tr.getStockPort().replaceAll("通道", "");
                                    stok = StringUtils.stripStart(stok, "0");
                                    try{
                                        if (cr.getId() == 48) { // 齐河
                                            //清空巷道
                                            this.hikAgvTaskService.clear2(stok);
                                        } else {
                                            HikRsVo hikRsVo = HikApiUtils.clearRoadWay(cr.getAgvBaseUrl(), stok);
                                        }
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                    if (ToolUtil.isNotEmpty(cr.getModeTms())) {
                        if (cr.getModeTms().equals("1") || cr.getModeTms().equals("3") || cr.getModeTms().equals("4")) {
                            for (OrderTransportResult r : list) {
                                if (ToolUtil.isNotEmpty(r.getOrderNumber())) {
                                    HxStorageStockParam stockParamdelete = new HxStorageStockParam();
                                    stockParamdelete.setStockState("集货");
                                    stockParamdelete.setStorageNumber(r.getOrderNumber());
                                    hxStorageStockService.deleteBySpec(stockParamdelete);//删除集货区库存

                                    hxStorageOutService.lambdaUpdate()
                                            .eq(HxStorageOut::getStorageNumber, r.getOrderNumber())
                                            .set(HxStorageOut::getStartState, "已发车")
                                            .update();//更新零售拣货任务 发车状态
                                }
                            }
                        }
                    }
                    if (ToolUtil.isNotEmpty(cr.getGsnumber()) && ToolUtil.isNotEmpty(cr.getStoreIdXlb())) {
                        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
                        oauth2tokenParam.setDeliverId(user.getDeliverId());
                        oauth2tokenParam.setGsnumber(cr.getGsnumber());
                        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
                        if (oauth2tokenResult != null) {
                            if (ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
                                if (list.size() > 0) {
                                    if (ToolUtil.isNotEmpty(cr.getModeTms()) && cr.getModeTms().equals("2")) {
                                        List<String> pick_order_ids = new ArrayList<String>();
                                        for (OrderTransportResult r : list) {
                                            if (ToolUtil.isNotEmpty(r.getOrderNumber())) {
                                                pick_order_ids.add(r.getOrderNumber());
                                            }
                                        }
                                        if (pick_order_ids.size() > 0) {
//        	    					        String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.depart";
                                            String url = this.hxlApiUrl+"/hxl.open.wms.depart";
                                            Map<String, String> map = new HashMap<>();
                                            map.put("plate_number", dispatchResult.getCarnumber());
                                            map.put("driver_name", dispatchResult.getSiji());
                                            map.put("driver_tel", dispatchResult.getSijidianhua());
                                            BigDecimal yibai = new BigDecimal("100");
                                            BasicPrivatecar basicPrivatecar = basicPrivatecarService.getById(dispatchResult.getCarId());
                                            try {
                                                if (ToolUtil.isNotEmpty(basicPrivatecar.getPrivatecarCarlong())) {
                                                    BigDecimal privatecarCarlong = new BigDecimal(basicPrivatecar.getPrivatecarCarlong());
                                                    BigDecimal privatecarCarlongmul = privatecarCarlong.multiply(yibai).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                                                    map.put("length", privatecarCarlongmul + "");
                                                }
                                                if (ToolUtil.isNotEmpty(basicPrivatecar.getPrivatecarCarwide())) {
                                                    BigDecimal privatecarCarwide = new BigDecimal(basicPrivatecar.getPrivatecarCarwide());
                                                    BigDecimal privatecarCarwidemul = privatecarCarwide.multiply(yibai).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                                                    map.put("width", privatecarCarwidemul + "");
                                                }
                                                if (ToolUtil.isNotEmpty(basicPrivatecar.getPrivatecarCarhigh())) {
                                                    BigDecimal privatecarCarhigh = new BigDecimal(basicPrivatecar.getPrivatecarCarhigh());
                                                    BigDecimal privatecarCarhighmul = privatecarCarhigh.multiply(yibai).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                                                    map.put("height", privatecarCarhighmul + "");
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                            JSONObject json = new JSONObject();
                                            json.put("store_id", cr.getStoreIdXlb());
                                            json.put("pick_order_fids", pick_order_ids);
                                            json.put("car", map);
                                            if (ToolUtil.isNotEmpty(cr.getNeedCheck())) {
                                                if (cr.getNeedCheck().equals("1")) {
                                                    json.put("need_check", "true");
                                                } else {
                                                    json.put("need_check", "false");
                                                }
                                            }
                                            json.put("operator", dispatchResult.getSiji());
                                            String post = HttpRequest.post(url)
                                                    .timeout(60000)
                                                    .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
//        	    							System.out.println("================json："+json+"========================");
//        	    							System.out.println("================post："+post+"========================");
                                            JSONObject jsonObject = new JSONObject(post);
                                            if (jsonObject.get("code").toString().equals("0")) {
                                                String depart_order_id = jsonObject.get("data").toString();
                                                if (ToolUtil.isNotEmpty(depart_order_id)) {
                                                    tDispatchParam.setXlbDepartOrderId(depart_order_id);
                                                } else {
                                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                                                    return ResponseData.error("发车单id为空");
                                                }
                                            } else {
                                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                                                String msg = jsonObject.get("msg").toString();
                                                return ResponseData.error(msg);
                                            }
                                        }
                                    }
                                    if (ToolUtil.isNotEmpty(cr.getModeTms()) && cr.getModeTms().equals("3") || cr.getModeTms().equals("4")) {
//    	    					        String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.depart.create";
                                        String url = this.hxlApiUrl+"/hxl.open.wms.depart.create";
                                        String trayCode = getOperateIdOrderPrefix(user);
                                        JSONArray jsonArray2 = new JSONArray();
                                        OrderTransportParam orderTransportParam2 = new OrderTransportParam();
                                        orderTransportParam2.setOrderNumber(dispatchResult.getDispatchNumber());
                                        List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo3(orderTransportParam2);
                                        if (list2.size() > 0) {
                                            List<OrderTransportResult> dblist = orderTransportService.findPieceNumberNumBySpec(dispatchResult.getDispatchNumber());
                                            for (OrderTransportResult r : list2) {
                                                JSONArray jsonArray = new JSONArray();
                                                TransportDispatchParam transportDispatchParam = new TransportDispatchParam();
                                                transportDispatchParam.setDispatchNumber(dispatchResult.getDispatchNumber());
                                                transportDispatchParam.setGetLocationId(r.getGetLocationId());
                                                List<TransportDispatchResult> dlist = transportDispatchService.findSumGoodsBySpec(transportDispatchParam);
                                                for (TransportDispatchResult dr : dlist) {
                                                    JSONObject jsonObject = new JSONObject();
                                                    jsonObject.put("basic_quantity", dr.getJibenNum());
                                                    jsonObject.put("basic_unit", dr.getJibenUnit());
                                                    if (ToolUtil.isNotEmpty(dr.getDemolition())) {
                                                        jsonObject.put("box_code", trayCode + "FX" + cn.stylefeng.guns.core.util.DateUtil.getDatesBch() + DateUtil.getRandomNumber());
                                                    }
                                                    if (ToolUtil.isNotEmpty(dr.getDaoqiDate())) {
                                                        jsonObject.put("expire_date", dr.getDaoqiDate() + " 00:00:00");
                                                    }
                                                    jsonObject.put("item_bar_code", dr.getGoodsPcode69());
                                                    jsonObject.put("item_code", dr.getGoodsNumber());
                                                    jsonObject.put("item_id", dr.getXlbGoodsId());
                                                    jsonObject.put("item_name", dr.getGoodsName());
                                                    jsonObject.put("item_spec", dr.getGoodsSpecs());
                                                    if (ToolUtil.isNotEmpty(dr.getDetailedDate())) {
                                                        jsonObject.put("producing_date", dr.getDetailedDate() + " 00:00:00");
                                                    }
                                                    jsonObject.put("quantity", dr.getTooDeployNum());
                                                    jsonObject.put("ratio", dr.getRate());
                                                    jsonObject.put("storage_id", dr.getXlbPositionId());
                                                    jsonObject.put("storage_name", dr.getPositionNumber());
                                                    jsonObject.put("unit", dr.getGoodsUnit());
                                                    jsonArray.put(jsonObject);
                                                }
                                                JSONObject jsonObject2 = new JSONObject();
                                                TransportDispatchResult resultzjclunit = transportDispatchService.findClZjunitSumBySpec(dispatchResult.getDispatchNumber(), r.getGetLocationId());
                                                if (resultzjclunit != null) {
                                                    jsonObject2.put("quantity", resultzjclunit.getZjsum());
//                                                    jsonObject2.put("demolition_item_quantity", resultzjclunit.getClsum().replaceAll("\\..*",""));
                                                    jsonObject2.put("volume", resultzjclunit.getTooDeployVolume());
                                                }
                                                BigDecimal dbNumSum = new BigDecimal("0");
                                                for (OrderTransportResult dbr : dblist) {
                                                    if (dbr.getGetLocationId().equals(r.getGetLocationId())) {
                                                        BigDecimal dbNum = new BigDecimal(dbr.getDbSum());
                                                        dbNumSum = dbNumSum.add(dbNum);
                                                    }
                                                }
                                                jsonObject2.put("demolition_item_quantity", (dbNumSum + "").replaceAll("\\..*", ""));
                                                jsonObject2.put("dump_quantity", "0");
                                                jsonObject2.put("client_id", r.getXlbClientId());
                                                jsonObject2.put("client_name", r.getGetUnit());
                                                jsonObject2.put("details", jsonArray);
                                                jsonObject2.put("order_fid", r.getLmAssociationOrder());
                                                if (ToolUtil.isNotEmpty(r.getLmOrderType())) {
                                                    if (r.getLmOrderType().equals("门店调出")) {
                                                        jsonObject2.put("order_type", "STORE_OUT");
                                                    }
                                                    if (r.getLmOrderType().equals("采购退货")) {
                                                        jsonObject2.put("order_type", "RETURN");
                                                    }
                                                    if (r.getLmOrderType().equals("批发销售")) {
                                                        jsonObject2.put("order_type", "WHOLESALE");
                                                    }
                                                    if (r.getLmOrderType().equals("调整出库")) {
                                                        jsonObject2.put("order_type", "ADJUST_OUT");
                                                    }
                                                    if (r.getLmOrderType().equals("仓间调拨")) {
                                                        jsonObject2.put("order_type", "TRANSFER");
                                                    }
                                                }
                                                jsonArray2.put(jsonObject2);
                                            }

                                            JSONObject json = new JSONObject();
                                            TransportDispatchResult resultzjcl = transportDispatchService.findClZjSumBySpec(dispatchResult.getDispatchNumber());
                                            if (resultzjcl != null) {
                                                json.put("quantity", resultzjcl.getZjsum());
//                                                json.put("demolition_item_quantity", resultzjcl.getClsum().replaceAll("\\..*",""));
                                            }
                                            BigDecimal dbNumSum = new BigDecimal("0");
                                            for (OrderTransportResult dbr : dblist) {
                                                BigDecimal dbNum = new BigDecimal(dbr.getDbSum());
                                                dbNumSum = dbNumSum.add(dbNum);
                                            }
                                            json.put("demolition_item_quantity", (dbNumSum + "").replaceAll("\\..*", ""));
                                            json.put("dump_quantity", "0");
                                            json.put("volume", dispatchResult.getToovolume());
                                            json.put("delivery_date", dispatchResult.getStartDate());
                                            json.put("client_count", list2.size());
                                            json.put("details", jsonArray2);
                                            json.put("driver_name", dispatchResult.getSiji());
                                            json.put("driver_phone", dispatchResult.getSijidianhua());
                                            json.put("number", dispatchResult.getCarnumber());
                                            json.put("store_id", list2.get(0).getXlbSetUnitId());
                                            json.put("store_name", list2.get(0).getSetUnit());
                                            json.put("storehouse_id", list2.get(0).getXlbSetWarehouseId());
                                            json.put("storehouse_name", list2.get(0).getXlbSetWarehouse());
                                            json.put("operator", user.getName());
                                            json.put("wms_fid", dispatchResult.getDispatchNumber());
                                            String post = HttpRequest.post(url)
                                                    .timeout(120000)
                                                    .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
//	    	    							System.out.println("================json："+json+"========================");
//	    	    							System.out.println("================post："+post+"========================");
                                            JSONObject jsonObject = new JSONObject(post);
                                            if (jsonObject.get("code").toString().equals("0")) {
                                                String depart_order_id = jsonObject.get("data").toString();
                                                if (ToolUtil.isNotEmpty(depart_order_id)) {
                                                    tDispatchParam.setXlbDepartOrderId(depart_order_id);
                                                } else {
                                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                                                    return ResponseData.error("发车单id为空");
                                                }
                                            } else {
                                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                                                String msg = jsonObject.get("msg").toString();
                                                return ResponseData.error(msg);
                                            }
                                        }
                                    }
//    	    						if(ToolUtil.isNotEmpty(cr.getAgvRobot())&&cr.getAgvRobot().equals("1")) {//清空海康巷道
//    	    				    		OrderTransportParam orderTransportParam2 = new OrderTransportParam();
//    	    				    		orderTransportParam2.setOrderNumber(dispatchResult.getDispatchNumber());
//    	    				    		List<OrderTransportResult> list2 = this.orderTransportService.findStockPort(orderTransportParam2);
//    	    							for (OrderTransportResult r : list2) {
//											if(cr.getId() == 48) {
//												String stockPort = r.getStockPort();
//												stockPort = stockPort.replaceAll("通道", "");
//												if(stockPort.substring(0,1).equals("0")) {
//													stockPort = stockPort.substring(1);
//												}
//												if(stockPort.substring(0,1).equals("0")) {
//													stockPort = stockPort.substring(1);
//												}
//												//清空巷道
//												hikAgvTaskService.clear2(stockPort);
////												HikRsVo res = HikApiUtils.clearRoadWay(hikBaseUrl, stockPort);
//											}
//										}
//
//    	    						}
//    	    						if(ToolUtil.isNotEmpty(cr.getAgvRobot())&&cr.getAgvRobot().equals("2")) {
//    	    				    		OrderTransportParam orderTransportParam2 = new OrderTransportParam();
//    	    				    		orderTransportParam2.setOrderNumber(dispatchResult.getDispatchNumber());
//    	    				    		List<OrderTransportResult> list2 = this.orderTransportService.findStockPort(orderTransportParam2);
//    	    							for (OrderTransportResult r : list2) {
//											if(cr.getId() == 60) {
//												FeedbackTaskRS res = TustApiUtils.clear(tuskBaseUrl, "H"+r.getStockPort().replaceAll("通道", ""));
//											}
//										}
//
//    	    						}
                                }
                            }
                        }
                    }
                    tDispatchParam.setId(dispatchResult.getId());
                    tDispatchParam.setFayunTimes(DateUtil.getDateS());
                    tDispatchParam.setTstate("运输中");
                    this.tDispatchService.update(tDispatchParam);

                    TransportMsgParam transportMsgParam = new TransportMsgParam();
                    transportMsgParam.setDispatchNumber(dispatchResult.getDispatchNumber());
                    transportMsgParam.setStatus("离场发运");
                    transportMsgParam.setMsgType("司机");
                    transportMsgParam.setContent("车辆已经离开发货地，运单正在运输中。" + "当前定位：" + currentAddress);
                    transportMsgParam.setTimes(DateUtil.getDateS());
                    transportMsgParam.setCreateUsername(user.getName());
                    transportMsgParam.setDeliverId(dispatchResult.getDeliverId());
                    transportMsgParam.setDeptId(dispatchResult.getDeptId());
                    transportMsgParam.setV2(user.getPhone());
                    transportMsgParam.setSfyz(sfyz);
                    transportMsgService.add(transportMsgParam);

                    TransportMsgParam dcqd = new TransportMsgParam();
                    dcqd.setV3(dispatchResult.getCarId() + "");
                    dcqd.setDeptId(dispatchResult.getDeptId());
                    dcqd.setStatus("到仓签到");
                    TransportMsgResult msgResult = transportMsgService.findDcqdBySpec(dcqd, dispatchResult.getOperateId());
                    if (msgResult != null) {
                        TransportMsgParam msgParam = new TransportMsgParam();
                        msgParam.setId(msgResult.getId());
                        msgParam.setV4("已发运");
                        transportMsgService.update(msgParam);
                    }

//                	Map<String,String> ttMap = new HashMap<>();
//                	for (TrayNumberVo t : trayNumbers) {
//						boolean update = hxCollectionLocationService.lambdaUpdate()
//								.eq(HxCollectionLocation::getTrayNumber, t.getResult())
//								.set(HxCollectionLocation::getStatus, null)
//								.set(HxCollectionLocation::getGetUnit, null)
//								.set(HxCollectionLocation::getGetUnitId, null)
//								.set(HxCollectionLocation::getTrayNumber, null)
//								.update();
//
//						if(update){
//							if(ttMap.get(t.getStockPort()) == null){
//								if(ToolUtil.isNotEmpty(cr.getAgvRobot())&&cr.getAgvRobot().equals("2")) {
//									if(ToolUtil.isNotEmpty(cr.getAgvBaseUrl())) {
//										String stok = t.getStockPort().replaceAll("通道", "");
//										FeedbackTaskRS res = TustApiUtils.clear(cr.getAgvBaseUrl(), "H"+ StringUtils.leftPad(stok,3,"0"));
//										if(res != null && res.getCode() == 200){
//											ttMap.put(t.getStockPort(),t.getStockPort());
//										}
//									}
//								} else if(ToolUtil.isNotEmpty(cr.getAgvRobot()) && cr.getAgvRobot().equals("1") ) {
//									if(ToolUtil.isNotEmpty(cr.getAgvBaseUrl())) {
//										String stok = t.getStockPort().replaceAll("通道", "");
//										HikRsVo hikRsVo = HikApiUtils.clearRoadWay(cr.getAgvBaseUrl(), stok);
//										if(hikRsVo != null && "0".equals(hikRsVo.getCode())){
//											ttMap.put(t.getStockPort(),t.getStockPort());
//										}
//									}
//                                }
//							}
//							ttMap.put(t.getStockPort(),t.getStockPort());
//						}
//					}
                }
            }
        }
        return ResponseData.success();
    }

    /**
     * 获取所属项目单号前缀
     *
     * @param user
     * @return
     */
    public String getOperateIdOrderPrefix(User user) {
        if (user.getOperateId() != null) {
            Dept dept = new Dept();
            dept.setOperateId(user.getOperateId());
            Dept resdept = deptService.findBySpec(dept);
            if (resdept != null) {
                if (ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
                    return resdept.getOrderPrefix();
                } else {
                    return user.getAccount().substring(0, 3);
                }
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Autowired
    private HxCollectionLocationService hxCollectionLocationService;

    @Value("${tusk.baseUrl}")
    private String tuskBaseUrl;

    @Value("${hik.baseUrl}")
    private String hikBaseUrl;

    @Autowired
    private DeptService deptService;

    /**
     * 送达
     */
    @RequestMapping("/editsongda")
    @ResponseBody
    public ResponseData editsongda(TDispatchParam tDispatchParam, String getUnitId, String getUnit, String currentAddress, String getLocationId, String getLocation, String sfyz) {
        User user = userAop.getUser();
        TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
        //解决参数中的 英文括号
        if (ToolUtil.isNotEmpty(currentAddress)) {
            currentAddress = currentAddress.replace("& #40;", "(");
            currentAddress = currentAddress.replace("& #41;", ")");
        }
        if (ToolUtil.isEmpty(sfyz)) {
            sfyz = "是";
        }
        TransportMsgParam transportMsgParam = new TransportMsgParam();
        transportMsgParam.setDispatchNumber(tDispatchParam.getDispatchNumber());
        transportMsgParam.setStatus("送达");
        transportMsgParam.setMsgType("司机");
        transportMsgParam.setContent(getUnit + getLocation + "已确认送达。" + "当前定位：" + currentAddress);
        transportMsgParam.setTimes(DateUtil.getDateS());
        transportMsgParam.setCreateUsername(user.getName());
        transportMsgParam.setDeliverId(dispatchResult.getDeliverId());
        transportMsgParam.setDeptId(dispatchResult.getDeptId());
        transportMsgParam.setV1(getLocationId);
        transportMsgParam.setV2(getUnit);
        transportMsgParam.setV3(getUnitId);
        transportMsgParam.setSfyz(sfyz);
        transportMsgService.add(transportMsgParam);
        return ResponseData.success();
    }

    /**
     * 上传送达签名照片
     *
     * @param file
     * @return
     */
    @RequestMapping("/uploadqianmingFile")
    @ResponseBody
    public ResponseData uploadqianmingFile(@RequestParam("file") MultipartFile file, Integer id, String longitude, String latitude, String currentAddress, String openId) {

        // 经纬度解析地址
        String location = longitude + "," + latitude;
        StringBuilder stringBuilder = new StringBuilder("https://restapi.amap.com/v3/geocode/regeo");
        stringBuilder.append("?key=4bb7b6534a7dd0bee729aa6d42e1f1f2");
        stringBuilder.append("&location=").append(location);
        stringBuilder.append("&radius=").append(200);
        stringBuilder.append("&extensions=").append("all");
        try {
            // 发送GET请求并获取响应
            String url = stringBuilder.toString();
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.getForObject(url, String.class);

            // 将字符串转换为JSONObject
            JSONObject jsonObject = new JSONObject(response);
            // 提取formatted_address
            if (jsonObject.optJSONObject("regeocode") != null) {
                JSONObject regeocode = jsonObject.optJSONObject("regeocode");
                currentAddress = regeocode.optString("formatted_address");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        User user = userAop.getUser();
        String fileId = "";
        String base64Image = "";
        try {
            fileId = this.fileInfoService.uploadFileTms(file);
            FileInfo fileInfo = fileInfoService.getById(fileId);

            Path path = Paths.get(fileInfo.getFilePath());
            byte[] imageBytes = Files.readAllBytes(path);
            base64Image = "data:image/" + fileInfo.getFileSuffix() + ";base64," + Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error("上传失败请重试");
        }
        TransportReceipt transportReceipt = transportReceiptService.getById(id);
        TDispatchParam tDispatchParam = new TDispatchParam();
        tDispatchParam.setDispatchNumber(transportReceipt.getDispatchNumber());
        TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);

        BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
        basicCustomerParam.setCustomerOperateId(Integer.parseInt(dispatchResult.getOperateId().toString()));
        BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
        if (cr != null) {
            if (ToolUtil.isNotEmpty(cr.getGsnumber()) && ToolUtil.isNotEmpty(cr.getStoreIdXlb())) {
                if (ToolUtil.isNotEmpty(transportReceipt.getXlbClientId()) && ToolUtil.isNotEmpty(dispatchResult.getXlbDepartOrderId())) {
                    BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
                    oauth2tokenParam.setDeliverId(user.getDeliverId());
                    oauth2tokenParam.setGsnumber(cr.getGsnumber());
                    BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
                    if (oauth2tokenResult != null) {
                        if (ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {

					        String url =this.hxlApiUrl+"/hxl.open.wms.arrive";
//                            String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.arrive";
                            JSONObject json = new JSONObject();
                            json.put("client_id", transportReceipt.getXlbClientId());
                            json.put("file_url", base64Image);
                            json.put("depart_order_fid", dispatchResult.getXlbDepartOrderId().replaceAll("\t\r\n", ""));
                            String post = HttpRequest.post(url)
                                    .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
//							System.out.println("================json："+json+"========================");
//							System.out.println("================post："+post+"========================");
                            JSONObject jsonObject = new JSONObject(post);
                            if (!jsonObject.get("code").toString().equals("0")) {
                                String msg = jsonObject.get("msg").toString();
                                return ResponseData.error(msg);
                            }
                        }
                    }
                }
            }
            TransportReceiptParam receiptParam = new TransportReceiptParam();
            receiptParam.setId(id);
            receiptParam.setSdfileId(fileId);
            receiptParam.setSdtime(DateUtil.getDateS());
            receiptParam.setSdtstate("已送达");
            receiptParam.setSdusername(user.getName());
            transportReceiptService.update(receiptParam);

            //解决参数中的 英文括号
            if (ToolUtil.isNotEmpty(currentAddress)) {
                currentAddress = currentAddress.replace("& #40;", "(");
                currentAddress = currentAddress.replace("& #41;", ")");
            }
            TransportMsgParam transportMsgParam = new TransportMsgParam();
            transportMsgParam.setDispatchNumber(transportReceipt.getDispatchNumber());
            transportMsgParam.setStatus("送达");
            transportMsgParam.setMsgType("司机");
            transportMsgParam.setContent(transportReceipt.getGetUnit() + transportReceipt.getGetLocation() + "已确认送达。" + "当前定位：" + currentAddress);
            transportMsgParam.setTimes(DateUtil.getDateS());
            transportMsgParam.setCreateUsername(user.getName());
            transportMsgParam.setDeliverId(transportReceipt.getDeliverId());
            transportMsgParam.setDeptId(transportReceipt.getDeptId());
            transportMsgParam.setV1(transportReceipt.getGetLocationid() + "");
            transportMsgParam.setV2(transportReceipt.getGetUnit());
            transportMsgParam.setV3(transportReceipt.getGetUnitid() + "");
            transportMsgParam.setV4(fileId);
            transportMsgParam.setSfyz("是");
            transportMsgParam.setOpenId(openId);
            transportMsgService.add(transportMsgParam);
        }
        return ResponseData.success();
    }

    /**
     * 主动 送达签名校验
     */
    @RequestMapping("/editsongdaqianmingjiaoyan")
    @ResponseBody
    public ResponseData editsongdaqianmingjiaoyan(Integer id, String longitude, String latitude, String openId) {
        if (ToolUtil.isEmpty(longitude) || ToolUtil.isEmpty(latitude) || id == null) {
            return ResponseData.error("缺少参数");
        }
        TransportReceipt transportReceipt = transportReceiptService.getById(id);
        if (transportReceipt != null) {
            if (ToolUtil.isNotEmpty(openId)) {
                TransportMsgParam msgParam = new TransportMsgParam();
                msgParam.setDispatchNumber(transportReceipt.getDispatchNumber());
                msgParam.setStatus("到仓装车");
                TransportMsgResult msgResult = transportMsgService.findBySpec(msgParam);
                if (msgResult != null) {
                    if (ToolUtil.isNotEmpty(msgResult.getOpenId())) {
                        if (!msgResult.getOpenId().equals(openId)) {
                            ResponseData data1 = new ResponseData();
                            data1.setCode(305);
                            data1.setMessage("当前微信与到仓微信账户不一致");
                            data1.setSuccess(false);
                            return data1;
                        }
                    }
                }
            }

            TDispatchParam tDispatchParam = new TDispatchParam();
            tDispatchParam.setDispatchNumber(transportReceipt.getDispatchNumber());
            TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
            if (dispatchResult != null) {
                if (dispatchResult.getOperateId() != null) {
                    BasicOperate basicOperate = basicOperateService.getById(dispatchResult.getOperateId());
                    if (basicOperate != null) {
                        if (ToolUtil.isNotEmpty(basicOperate.getCheckWl())) {
                            if (basicOperate.getCheckWl().equals("否")) {
                                return ResponseData.success();
                            }
                        }
                    }
                }
            }

            BasicAddress basicAddress = basicAddressService.getById(transportReceipt.getGetLocationid());
            if (basicAddress != null) {
                if (ToolUtil.isNotEmpty(basicAddress.getSwitchWl())) {
                    if (basicAddress.getSwitchWl().equals("1")) {
                        if (ToolUtil.isNotEmpty(basicAddress.getLongitude()) && ToolUtil.isNotEmpty(basicAddress.getLatitude())) {
                            double a = MapUtils.GetDistance(Double.parseDouble(basicAddress.getLongitude()), Double.parseDouble(basicAddress.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
                            double radius = Double.parseDouble(basicAddress.getSwitchBj2());
                            if (radius < a) {
                                ResponseData data1 = new ResponseData();
                                data1.setCode(306);
                                data1.setMessage("您所在位置超出收货范围");
                                data1.setSuccess(false);
                                return data1;
                            }
                        }
                    }
                }
            }
        }
        return ResponseData.success();
    }

    /**
     * 主动 送达校验
     */
    @RequestMapping("/editsongdajiaoyan")
    @ResponseBody
    public ResponseData editsongdajiaoyan(Long getLocationId, String longitude, String latitude) {
        if (ToolUtil.isEmpty(longitude) || ToolUtil.isEmpty(latitude) || getLocationId == null) {
            return ResponseData.error("缺少参数");
        }

        BasicAddress basicAddress = basicAddressService.getById(getLocationId);
        if (basicAddress != null) {
            if (ToolUtil.isNotEmpty(basicAddress.getSwitchWl())) {
                if (basicAddress.getSwitchWl().equals("1")) {
                    if (ToolUtil.isNotEmpty(basicAddress.getLongitude()) && ToolUtil.isNotEmpty(basicAddress.getLatitude())) {
                        double a = MapUtils.GetDistance(Double.parseDouble(basicAddress.getLongitude()), Double.parseDouble(basicAddress.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
                        double radius = Double.parseDouble(basicAddress.getSwitchBj2());
                        if (radius < a) {
                            return ResponseData.error("您所在位置超出收货范围");
                        }
                    }
                }
            }
        }
        return ResponseData.success();
    }

    /**
     * 运输信息
     */
    @RequestMapping("/transportMsg")
    @ResponseBody
    public ResponseData transportMsg(TDispatchParam tDispatchParam) {
        TransportMsgParam transportMsgParam = new TransportMsgParam();
        transportMsgParam.setDispatchNumber(tDispatchParam.getDispatchNumber());
        List<TransportMsgResult> list = transportMsgService.findListBySpec(transportMsgParam, null);
        for (TransportMsgResult r : list) {
            r.setV1("1");
            break;
        }
        return ResponseData.success(list);
    }

    @Autowired
    private TransportReceiptService transportReceiptService;

    /**
     * 查询回传单
     */
    @RequestMapping("/transportReceipt")
    @ResponseBody
    public ResponseData transportReceipt(TransportReceiptParam transportReceiptParam) {
        List<TransportReceiptResult> list = transportReceiptService.findListBySpec(transportReceiptParam, null);
        return ResponseData.success(list);
    }

    @Autowired
    private FileInfoService fileInfoService;

    /**
     * 签收 校验
     */
    @RequestMapping("/editqianshoujiaoyan")
    @ResponseBody
    public ResponseData editqianshoujiaoyan(Integer id, String longitude, String latitude) {
        if (ToolUtil.isEmpty(longitude) || ToolUtil.isEmpty(latitude) || id == null) {
            return ResponseData.error("缺少参数");
        }
        TransportReceipt transportReceipt = transportReceiptService.getById(id);
        if (transportReceipt != null) {
            BasicAddress basicAddress = basicAddressService.getById(transportReceipt.getGetLocationid());
            if (basicAddress != null) {
                if (ToolUtil.isNotEmpty(basicAddress.getSwitchWl())) {
                    if (basicAddress.getSwitchWl().equals("1")) {
                        if (ToolUtil.isNotEmpty(basicAddress.getLongitude()) && ToolUtil.isNotEmpty(basicAddress.getLatitude())) {
                            double a = MapUtils.GetDistance(Double.parseDouble(basicAddress.getLongitude()), Double.parseDouble(basicAddress.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
                            double radius = Double.parseDouble(basicAddress.getSwitchBj2());
                            if (radius < a) {
//    							return ResponseData.error("您所在位置超出收货范围");
                            }
                        }
                    }
                }
            }
        }
        return ResponseData.success();
    }

    /**
     * 上传装载照片
     *
     * @param file
     * @return
     */
    @RequestMapping("/uploadzhuangzaiFile")
    @ResponseBody
    public ResponseData uploadzhuangzaiFile(@RequestParam("file") MultipartFile file, String dispatchNumber) {
        ResponseData responseData = ResponseData.success();
        responseData.setMessage("");

        String fileId = this.fileInfoService.uploadFileTms(file);
        UpdateWrapper<TDispatch> updateWrapper = new UpdateWrapper<TDispatch>();
        updateWrapper.set("zhuangzai_fileid", fileId);
        updateWrapper.eq("dispatch_number", dispatchNumber);
        tDispatchService.update(updateWrapper);
        try {
            //查询对应门店信息
            //只针对天津好想来项目【44】
            TDispatchResult tDispatchResult = tDispatchService.findByDispatchNumber(dispatchNumber);
            if (tDispatchResult != null && tDispatchResult.getOperateId() == 44 && ToolUtil.isNotEmpty(tDispatchResult.getTransportNumber())) {
                String transportNumber = tDispatchResult.getTransportNumber().split(";")[0];
                OrderTransportParam q1 = new OrderTransportParam();
                q1.setTransportNumber(transportNumber);
                OrderTransportResult orderTransportResult = orderTransportService.findBySpec(q1, tDispatchResult.getOperateId());
                if (orderTransportResult != null) {
                    //根据门店查询当前未完成的拣货单
                    List<HxStorageOutResult> hxStorageOutResults = hxStorageOutService.queryByGetUnitId(orderTransportResult.getGetUnitId());
                    if (hxStorageOutResults != null && hxStorageOutResults.size() > 0) {
                        responseData.setMessage("还有货物在进货中，请确认是否装车完成！");
                    }
                    //根据门店查询是否有待调的货运订单
                    String nowDate = DateUtil.getDate();
                    String now_3_Date = DateUtil.getPastDate(3);
                    OrderTransportParam q3 = new OrderTransportParam();
                    q3.setDeptId(tDispatchResult.getDeptId());
                    q3.setGetUnitId(orderTransportResult.getGetUnitId());
                    q3.setTstate("dispatch");
                    q3.setTimeInterval("'" + nowDate + "' and '" + now_3_Date + "' ");
                    List<OrderTransportResult> listBySpecByGetUnitId = orderTransportService.findListBySpecByGetUnitId(q3, tDispatchResult.getOperateId());
                    if (listBySpecByGetUnitId != null && listBySpecByGetUnitId.size() > 0) {
                        responseData.setMessage("还有货物未完成装车，请确认是否装车完成！");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseData;
    }

    /**
     * 上传封车照片
     */
    @RequestMapping("/closeCarfengcheFile")
    @ResponseBody
    public ResponseData closeCarfengcheFile(@RequestParam("file") MultipartFile file, String dispatchNumber) {
        ResponseData responseData = ResponseData.success();
        responseData.setMessage("");

        String fileId = this.fileInfoService.uploadFileTms(file);
        UpdateWrapper<TDispatch> updateWrapper = new UpdateWrapper<TDispatch>();
        updateWrapper.set("fengche_fileid", fileId);
        updateWrapper.eq("dispatch_number", dispatchNumber);
        tDispatchService.update(updateWrapper);
        try {
            //查询对应门店信息
            //只针对天津好想来项目【44】
            TDispatchResult tDispatchResult = tDispatchService.findByDispatchNumber(dispatchNumber);
            if (tDispatchResult != null && tDispatchResult.getOperateId() == 44 && ToolUtil.isNotEmpty(tDispatchResult.getTransportNumber())) {
                String transportNumber = tDispatchResult.getTransportNumber().split(";")[0];
                OrderTransportParam q1 = new OrderTransportParam();
                q1.setTransportNumber(transportNumber);
                OrderTransportResult orderTransportResult = orderTransportService.findBySpec(q1, tDispatchResult.getOperateId());
                if (orderTransportResult != null) {
                    //根据门店查询当前未完成的拣货单
                    List<HxStorageOutResult> hxStorageOutResults = hxStorageOutService.queryByGetUnitId(orderTransportResult.getGetUnitId());
                    if (hxStorageOutResults != null && hxStorageOutResults.size() > 0) {
                        responseData.setMessage("还有货物在进货中，请确认是否装车完成！");
                    }
                    //根据门店查询是否有待调的货运订单
                    String nowDate = DateUtil.getDate();
                    String now_3_Date = DateUtil.getPastDate(3);
                    OrderTransportParam q3 = new OrderTransportParam();
                    q3.setDeptId(tDispatchResult.getDeptId());
                    q3.setGetUnitId(orderTransportResult.getGetUnitId());
                    q3.setTstate("dispatch");
                    q3.setTimeInterval("'" + nowDate + "' and '" + now_3_Date + "' ");
                    List<OrderTransportResult> listBySpecByGetUnitId = orderTransportService.findListBySpecByGetUnitId(q3, tDispatchResult.getOperateId());
                    if (listBySpecByGetUnitId != null && listBySpecByGetUnitId.size() > 0) {
                        responseData.setMessage("还有货物未完成装车，请确认是否装车完成！");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseData;
    }


    /**
     * 签收上传回传单
     *
     * @param file
     * @return
     */
    @RequestMapping("/uploads")
    @ResponseBody
    public ResponseData uploads(@RequestParam("file") MultipartFile file, Integer id, String currentAddress, String sfyz) {
        String fileId = this.fileInfoService.uploadFileTms(file);
        //解决参数中的 英文括号
        if (ToolUtil.isNotEmpty(currentAddress)) {
            currentAddress = currentAddress.replace("& #40;", "(");
            currentAddress = currentAddress.replace("& #41;", ")");
        }
        if (ToolUtil.isEmpty(sfyz)) {
            sfyz = "是";
        }
        TransportReceipt transportReceipt = transportReceiptService.getById(id);
        User user = userAop.getUser();
        TransportReceiptParam param = new TransportReceiptParam();
        param.setId(id);
        param.setFileId(fileId);
        param.setTime(DateUtil.getDateS());
        param.setUsername(user.getName());
        param.setTstate("已回传");
        transportReceiptService.update(param);

        TransportMsgParam transportMsgParam = new TransportMsgParam();
        transportMsgParam.setStatus("客户签收");
        transportMsgParam.setDispatchNumber(transportReceipt.getDispatchNumber());
        transportMsgParam.setV1(transportReceipt.getGetLocationid().toString());
        TransportMsgResult transportMsgResult = transportMsgService.findBySpec(transportMsgParam);
        if (transportMsgResult != null) {
            transportMsgParam.setMsgType("司机");
            transportMsgParam.setContent(user.getName() + "签收并上传了回单，单位为：" + transportReceipt.getGetUnit() + "。" + "当前定位：" + currentAddress);
            transportMsgParam.setTimes(DateUtil.getDateS());
            transportMsgParam.setCreateUsername(user.getName());
            transportMsgParam.setDeliverId(transportReceipt.getDeliverId());
            transportMsgParam.setDeptId(transportReceipt.getDeptId());
            transportMsgParam.setV4(fileId);
            transportMsgParam.setSfyz(sfyz);
            transportMsgParam.setId(transportMsgResult.getId());
            transportMsgService.update(transportMsgParam);
        } else {
            transportMsgParam.setMsgType("司机");
            transportMsgParam.setContent(user.getName() + "签收并上传了回单，单位为：" + transportReceipt.getGetUnit() + "。" + "当前定位：" + currentAddress);
            transportMsgParam.setTimes(DateUtil.getDateS());
            transportMsgParam.setCreateUsername(user.getName());
            transportMsgParam.setDeliverId(transportReceipt.getDeliverId());
            transportMsgParam.setDeptId(transportReceipt.getDeptId());
            transportMsgParam.setV2(transportReceipt.getGetUnit());
            transportMsgParam.setV3(transportReceipt.getGetUnitid().toString());
            transportMsgParam.setV4(fileId);
            transportMsgParam.setSfyz(sfyz);
            transportMsgService.add(transportMsgParam);
        }
        return ResponseData.success();
    }

    /**
     * 删除回传文件
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteFile")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData deleteFile(String id) {
        // 1.修改回传单表状态，删除fileId
        TransportReceipt byId = transportReceiptService.getById(id);
        byId.setFileId(StrUtil.EMPTY);
        byId.setTstate("未回传");
        TransportReceiptParam param = new TransportReceiptParam();
        BeanUtil.copyProperties(byId, param);
        transportReceiptService.update(param);

        // 2.获取 fileId 清理 sys_file_info 内文件
        String fileId = byId.getFileId();
        this.fileInfoService.remove(new QueryWrapper<FileInfo>()
                .eq("file_id", fileId));

        return ResponseData.success("文件删除成功");
    }

    /**
     * 只签收
     *
     * @param
     * @return
     */
    @RequestMapping("/uploadsqs")
    @ResponseBody
    public ResponseData uploadsqs(Integer id, String currentAddress, String sfyz) {
        //解决参数中的 英文括号
        if (ToolUtil.isNotEmpty(currentAddress)) {
            currentAddress = currentAddress.replace("& #40;", "(");
            currentAddress = currentAddress.replace("& #41;", ")");
        }
        if (ToolUtil.isEmpty(sfyz)) {
            sfyz = "是";
        }
        TransportReceipt transportReceipt = transportReceiptService.getById(id);
        User user = userAop.getUser();

        TransportMsgParam transportMsgParam = new TransportMsgParam();
        transportMsgParam.setStatus("客户签收");
        transportMsgParam.setDispatchNumber(transportReceipt.getDispatchNumber());
        transportMsgParam.setV1(transportReceipt.getGetLocationid().toString());
        TransportMsgResult transportMsgResult = transportMsgService.findBySpec(transportMsgParam);
        if (transportMsgResult != null) {
            transportMsgParam.setMsgType("司机");
            transportMsgParam.setContent(user.getName() + "确认签收，单位为：" + transportReceipt.getGetUnit() + "。" + "当前定位：" + currentAddress);
            transportMsgParam.setTimes(DateUtil.getDateS());
            transportMsgParam.setCreateUsername(user.getName());
            transportMsgParam.setDeliverId(transportReceipt.getDeliverId());
            transportMsgParam.setDeptId(transportReceipt.getDeptId());
            transportMsgParam.setSfyz(sfyz);
            transportMsgParam.setId(transportMsgResult.getId());
            transportMsgService.update(transportMsgParam);
        } else {
            transportMsgParam.setMsgType("司机");
            transportMsgParam.setContent(user.getName() + "确认签收，单位为：" + transportReceipt.getGetUnit() + "。" + "当前定位：" + currentAddress);
            transportMsgParam.setTimes(DateUtil.getDateS());
            transportMsgParam.setCreateUsername(user.getName());
            transportMsgParam.setDeliverId(transportReceipt.getDeliverId());
            transportMsgParam.setDeptId(transportReceipt.getDeptId());
            transportMsgParam.setV2(transportReceipt.getGetUnit());
            transportMsgParam.setV3(transportReceipt.getGetUnitid().toString());
            transportMsgParam.setSfyz(sfyz);
            transportMsgService.add(transportMsgParam);
        }
        return ResponseData.success();
    }

    @Autowired
    private BasicPrivatecarService basicPrivatecarService;

    /**
     * APP(已发货) 完成
     */
    @RequestMapping("/accomplishUnitGoods")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData accomplishUnitGoods(TDispatchParam tDispatchParam) {
        User user = userAop.getUser();
        TDispatchResult tDispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
        if (tDispatchResult == null) {
            return ResponseData.success();
        }
        //校验送达 签收
        Integer rcount = transportReceiptService.countcheckzhixing(tDispatchResult.getDispatchNumber());
        if (rcount > 0) {
            return ResponseData.error("配送节点操作不完整");
        }

        //更新运输单
        tDispatchParam.setId(tDispatchResult.getId());
        tDispatchParam.setCompleteName(user.getName());
        tDispatchParam.setCompleteTimes(DateUtil.getDateS());
        tDispatchParam.setTstate("已完成");
        tDispatchService.update(tDispatchParam);

        //更新派车明细中 换算数量
//    		TransportDispatchParam hsParam = new TransportDispatchParam();
//    		hsParam.setDispatchNumber(tDispatchResult.getDispatchNumber());
//    		List<TransportDispatchResult> hslist = transportDispatchService.findListBySpecXianggui(hsParam);
//    		for (TransportDispatchResult i : hslist) {
//				try {
//					BigDecimal tooDeployNum = new BigDecimal(i.getTooDeployNum());
//					BigDecimal xianggui = new BigDecimal(i.getXianggui());
//					BigDecimal matrixingNumber = tooDeployNum.divide(xianggui, 2, BigDecimal.ROUND_HALF_DOWN);
//					TransportDispatchParam update = new TransportDispatchParam();
//					update.setId(i.getId());
//					update.setMatrixingNumber(matrixingNumber.toString());
//					transportDispatchService.update(update);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}

        //更新货运订单
        TransportDispatchParam transportDispatchParam = new TransportDispatchParam();
        transportDispatchParam.setDispatchNumber(tDispatchResult.getDispatchNumber());
        List<TransportDispatchResult> tdrlist = transportDispatchService.findOrderListBySpec(transportDispatchParam, "已发运", null);
        for (TransportDispatchResult dr : tdrlist) {
            TransportDispatchParam transportDispatchParam2 = new TransportDispatchParam();
            transportDispatchParam2.setTransportNumber(dr.getTransportNumber());
            transportDispatchParam2.setDispatchNumber(tDispatchResult.getDispatchNumber());
            List<TransportDispatchResult> tdrlist2 = transportDispatchService.findNotByCarnumber(transportDispatchParam2);
            if (tdrlist2.size() == 0) {
                orderTransportService.lambdaUpdate()
                        .eq(OrderTransport::getTransportNumber, dr.getTransportNumber())
                        .set(OrderTransport::getTstate, "已完成")
                        .update();
            }
        }

        //修改车辆
        BasicPrivatecar bpcr = basicPrivatecarService.getById(tDispatchResult.getCarId());
        TDispatchParam tDispatchParamf = new TDispatchParam();
        tDispatchParamf.setCarId(tDispatchResult.getCarId());
        tDispatchParamf.setDispatchNumber(tDispatchParam.getDispatchNumber());
        TDispatchResult tDispatchResultf = tDispatchService.findByYunshuCar(tDispatchParamf, null);
        if (tDispatchResultf == null) {//如果该车没有别的派车单
            if (bpcr != null) {
                BasicPrivatecarParam bpcp = new BasicPrivatecarParam();
                bpcp.setId(bpcr.getId());
                bpcp.setPrivatecarState("空闲");
                basicPrivatecarService.update(bpcp);
            }
        }

        TransportMsgParam transportMsgParam = new TransportMsgParam();
        transportMsgParam.setStatus("配送完成");
        transportMsgParam.setDispatchNumber(tDispatchResult.getDispatchNumber());
        transportMsgParam.setMsgType("司机");
        transportMsgParam.setContent(user.getName() + "确认配送完成。");
        transportMsgParam.setTimes(DateUtil.getDateS());
        transportMsgParam.setCreateUsername(user.getName());
        transportMsgParam.setDeliverId(tDispatchResult.getDeliverId());
        transportMsgParam.setDeptId(tDispatchResult.getDeptId());
        transportMsgService.add(transportMsgParam);
        return ResponseData.success();
    }

    @Autowired
    private TransportAddressEditService transportAddressEditService;

    /**
     * 提交地址修改申请
     *
     * @author zhucx
     * @Date 2023-11-21
     */
    @RequestMapping("/addressEditapplyfor")
    @ResponseBody
    public ResponseData addressEditapplyfor(TransportAddressEditParam transportAddressEditParam) {
        String getLocation = transportAddressEditParam.getGetLocation();
        if (getLocation != null && getLocation != "") {
            getLocation = getLocation.replace("& #40;", "(");
            getLocation = getLocation.replace("& #41;", ")");
            transportAddressEditParam.setGetLocation(getLocation);
        }
        User user = userAop.getUser();
        TDispatchParam tDispatchParam = new TDispatchParam();
        tDispatchParam.setDispatchNumber(transportAddressEditParam.getDispatchNumber());
        TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
        transportAddressEditParam.setState("待处理");
        transportAddressEditParam.setCarId(dispatchResult.getCarId());
        transportAddressEditParam.setCarnumber(dispatchResult.getCarnumber());
        transportAddressEditParam.setCreateBy(user.getName());
        transportAddressEditParam.setDeptId(dispatchResult.getDeptId());
        transportAddressEditParam.setDeliverId(dispatchResult.getDeliverId());
        this.transportAddressEditService.add(transportAddressEditParam);
        return ResponseData.success();
    }

    /**
     * 提交地址修改申请
     *
     * @author zhucx
     * @Date 2023-11-21
     */
    @RequestMapping("/addressEditapplyfor_songdaqianming")
    @ResponseBody
    public ResponseData addressEditapplyfor_songdaqianming(Integer rid, String longitude, String latitude, String currentAddress) {
        TransportAddressEditParam transportAddressEditParam = new TransportAddressEditParam();
        if (currentAddress != null && currentAddress != "") {
            currentAddress = currentAddress.replace("& #40;", "(");
            currentAddress = currentAddress.replace("& #41;", ")");
            transportAddressEditParam.setGetLocation(currentAddress);
        }
        User user = userAop.getUser();
        TransportReceipt transportReceipt = transportReceiptService.getById(rid);
        transportAddressEditParam.setState("待处理");
        transportAddressEditParam.setDispatchNumber(transportReceipt.getDispatchNumber());
        transportAddressEditParam.setGetUnitid(transportReceipt.getGetUnitid());
        transportAddressEditParam.setGetUnit(transportReceipt.getGetUnit());
        transportAddressEditParam.setGetLocationid(transportReceipt.getGetLocationid());
        transportAddressEditParam.setLongitude(longitude);
        transportAddressEditParam.setLatitude(latitude);
        transportAddressEditParam.setCarId(transportReceipt.getCarId());
        transportAddressEditParam.setCarnumber(transportReceipt.getCarnumber());
        transportAddressEditParam.setCreateBy(user.getName());
        transportAddressEditParam.setDeptId(transportReceipt.getDeptId());
        transportAddressEditParam.setDeliverId(transportReceipt.getDeliverId());
        this.transportAddressEditService.add(transportAddressEditParam);
        return ResponseData.success();
    }

    /**
     * 围栏校验 示例
     */
    @RequestMapping("/jingwei_checkdemo")
    @ResponseBody
    public ResponseData jingwei_checkdemo(Long setLocationId, String longitude, String latitude) {
        if (ToolUtil.isEmpty(longitude) || ToolUtil.isEmpty(latitude) || setLocationId == null) {
            return ResponseData.error("缺少参数");
        }

        BasicAddress basicAddress = basicAddressService.getById(setLocationId);
        if (basicAddress != null) {
            if (ToolUtil.isNotEmpty(basicAddress.getLongitude()) && ToolUtil.isNotEmpty(basicAddress.getLatitude())) {
                double a = MapUtils.GetDistance(Double.parseDouble(basicAddress.getLongitude()), Double.parseDouble(basicAddress.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
                double radius = Double.parseDouble(basicAddress.getSwitchBj());
                if (radius < a) {
                    return ResponseData.error("您所在位置超出提货范围");
                }
            }
        }
        return ResponseData.success();
    }

}
